package cz.data.auth.listener;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import cz.data.auth.service.SecurityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class NacosInstanceChangeListener extends Subscriber<InstancesChangeEvent>
        implements InitializingBean {

    @Autowired
    SecurityService securityService;
    @Resource
    NacosDiscoveryProperties properties;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 注册进nacos发布订阅中心
        NotifyCenter.registerSubscriber(this);
    }

    @Override
    public void onEvent(InstancesChangeEvent event) {
        String serviceName = event.getServiceName();
        if (StringUtils.equals(properties.getService(), serviceName))
            return;
        log.info("监听到nacos节点变更: {}-{}", event.getGroupName(), serviceName);
        List<ServiceInstance> instances = NacosServiceDiscovery.hostToServiceInstanceList(
                event.getHosts(), event.getServiceName());
        securityService.refreshServiceCache(serviceName, instances);
    }

    @Override
    public Class<? extends Event> subscribeType() {
        return InstancesChangeEvent.class;
    }


}
